//
//  DHTabViewController.m
//  DeepBreathingFramework
//
//  Created by DreamHack on 15-8-11.
//  Copyright (c) 2015年 DreamHack. All rights reserved.
//


#import "DHTabViewController.h"
#import "CYYLoadViewController.h"

typedef NS_ENUM(NSUInteger, ViewTag) {
    ButtonTag = 100
};

@interface DHTabViewController ()

@property (nonatomic, copy)   NSArray * viewControllers;
@property (nonatomic, copy)   NSArray * barItemImages;
@property (nonatomic, assign) NSUInteger selectedControllerIndex;
@property (nonatomic, strong) UIView * buttonContainerView;
@property (nonatomic, strong) UIView * childControllerContainerView;

- (void)initializeAppearance;

@end

@implementation DHTabViewController

#pragma mark - initializer
- (instancetype)initWithViewControllers:(NSArray *)viewControllers
{
    self = [self initWithViewControllers:viewControllers barItemImages:@[]];
    
    return self;
}

- (instancetype)initWithViewControllers:(NSArray *)viewControllers barItemImages:(NSArray *)barItemImages
{
    self = [super init];
    if (self) {
        self.selectedControllerIndex = 0;
        self.viewControllers = viewControllers;
        self.barItemImages = barItemImages;
    }
    return self;
}

- (instancetype)init
{
    self = [self initWithViewControllers:@[]];
    return self;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeAppearance];
}

#pragma mark - action/callback
- (void)action_onButton:(UIButton *)sender
{
    //非自动登录+不是点击的第一个键
    if (![[UserModel defaultUser] isAlreadyLoad] && sender.tag != 100) {
        [[[ControllerManager sharedManager] mainTabController] presentViewController:[[ControllerManager sharedManager] loadViewController] animated:YES completion:nil];
        return;
    }
    NSUInteger index = sender.tag - ButtonTag;
    if (index == self.selectedControllerIndex) {
        return;
    }
    if (index != 0 && self.view.subviews.count > 2) {
        [self.view.subviews.lastObject removeFromSuperview];
    }
    
    NSUInteger currentButtonTag = self.selectedControllerIndex + ButtonTag;
    UIButton * currentButton = (UIButton *)[self.buttonContainerView viewWithTag:currentButtonTag];
    currentButton.selected = NO;
    sender.selected = YES;
    
    // 移除当前显示的controller
    UIViewController * currentController = self.viewControllers[self.selectedControllerIndex];
    
    [currentController.view removeFromSuperview];
    [currentController removeFromParentViewController];
    [currentController willMoveToParentViewController:nil];
    
    // 加载选择的controller
    UIViewController * selectedController = self.viewControllers[index];
    [self addChildViewController:selectedController];
    
    self.selectedControllerIndex = index;
}

#pragma mark - system protocol implentations

#pragma mark - custom protocol implentations

#pragma mark - private methods

-(void)presentFirstViewController{
    if (self.viewControllers.count == 0 || self.selectedControllerIndex == 0) {
        return;
    }
    UIButton *firstButton = (UIButton *)[self.buttonContainerView viewWithTag:ButtonTag];
    [self action_onButton:firstButton];
}

- (void)initializeAppearance
{
    if (self.viewControllers.count == 0) {
        return;
    }
    
    [self.view addSubview:self.childControllerContainerView];
    [self.view addSubview:self.buttonContainerView];
    
    // 按钮图标数组
    _barItemImages = @[@"1000-0",@"1001-0",@"1002-0",@"1000-1",@"1001-1",@"1002-1"];
    
    // 默认加载第一个controller的内容
    UIViewController * firstViewController = self.viewControllers.firstObject;
    [self addChildViewController:firstViewController];
    
    // tabbarbutton的宽度
    CGFloat buttonWidth = CGRectGetWidth(self.view.bounds) / self.viewControllers.count;
    
    // 循环创建tabbarbutton
    [self.viewControllers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:@selector(action_onButton:) forControlEvents:UIControlEventTouchUpInside];
        [button setFrame:CGRectMake(idx * buttonWidth, 10*DHFlexibleVerticalMutiplier(), buttonWidth, 30*DHFlexibleVerticalMutiplier())];
        if (self.barItemImages.count > 0) {
            [button setImage:[UIImage imageNamed:self.barItemImages[idx]] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:self.barItemImages[idx + 3]] forState:UIControlStateSelected];
            button.imageView.contentMode = UIViewContentModeScaleAspectFit;
            
        } else {
            [button setTitle:[NSString stringWithFormat:@"%lu",idx+1] forState:UIControlStateNormal];
        }
        button.tag = ButtonTag+idx;
        [self.buttonContainerView addSubview:button];
    }];
    
    // 设置button选中
    NSUInteger currentButtonTag = self.selectedControllerIndex + ButtonTag;
    UIButton * currentButton = (UIButton *)[self.buttonContainerView viewWithTag:currentButtonTag];
    currentButton.selected = YES;
}

//跳转到制定的界面
- (void)goToViewWithIndex:(NSInteger)index{
    [self action_onButton:((UIButton *)[self.view viewWithTag:100 + index])];
}

#pragma mark - override
- (void)addChildViewController:(UIViewController *)childController
{
    [self.childControllerContainerView addSubview:childController.view];
    [super addChildViewController:childController];
    [childController didMoveToParentViewController:self];
}

#pragma mark - getter

- (UIView *)buttonContainerView
{
    if (!_buttonContainerView) {
        _buttonContainerView = ({
            UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - TABBAR_Height * DHFlexibleVerticalMutiplier(), self.view.bounds.size.width, TABBAR_Height * DHFlexibleVerticalMutiplier())];
            view.backgroundColor = [UIColor whiteColor];
            view;
        });
    }
    return _buttonContainerView;
}

- (UIView *)childControllerContainerView
{
    if (!_childControllerContainerView) {
        _childControllerContainerView = ({
            UIView * view = [[UIView alloc] initWithFrame:self.view.bounds];
            view;
        });
    }
    
    return _childControllerContainerView;
}

@end
